import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { SFSchema, SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';

import { FreightAccountService } from '../../services/freight-account.service';

@Component({
  selector: 'app-withdrawals-record',
  templateUrl: './withdrawals-record.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class WithdrawalsRecordComponent extends BasicTableComponent {
  @ViewChild('auditModal', { static: false })
  auditModal!: any;
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();

  selectedRows: any[] = [];
  totalCallNo = 0;
  refundStatus: any = '';

  msg = '';
  constructor(
    public service: FreightAccountService,
    private nzModalService: NzModalService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  ngOnInit(): void {}

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        createTime: {
          start: this.sf?.value.createTime?.[0] || '',
          end: this.sf?.value.createTime?.[1] || ''
        }
      });
    }
    delete requestOptions?.body?.expand;
    this.selectedRows = [];
    this.totalCallNo = 0;
    Object.assign(requestOptions.body, { refundStatus: this.refundStatus || null });
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    data = data.map(node => ({ ...node,
       disabled: node.refundStatus !== '1' 
      }));
    return data;
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.amount, 0).toFixed(2);
        break;
    }
  }

  changeRefundStatus(status?: string) {
    this.refundStatus = status || null;
    this.st.load(1);
  }

  auditAction(item?: any) {
    this.msg = '';
    let params: string[] = [];
    if (item) {
      params = [item.id];
    } else {
      console.log(this.selectedRows);

      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('请选择提现单！');
        return;
      }
      params = this.selectedRows.map(node => node.id);
    }
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          disabled: () => this.service.http.loading,
          type: 'default',
          onClick: () => {
            if (!this.msg || this.msg.trim().length === 0) {
              this.service.msgSrv.warning('请填写拒绝原因 ');
              return false;
            }
            this.service
              .request(this.service.$api_disagree_refund, {
                refundApplicationId: params,
                msg: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核拒绝成功');
                  modal.destroy();
                  this.st.load(1);
                }
              });
            return false;
          }
        },
        {
          label: '通过',
          disabled: () => this.service.http.loading,
          type: 'primary',
          onClick: () => {
            this.service
              .request(this.service.$api_agree_refund, {
                refundApplicationId: params,
                msg: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核通过成功');
                  modal.destroy();
                  this.st.load(1);
                }
              });
            return false;
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: '运单数据异常，暂时无法开票，请联系客服400-xxxx-xxxx',
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        refundApplyCode: {
          type: 'string',
          title: '提现单号',
          ui: {
            placeholder: '请输入'
          }
        },
        createTime: {
          title: '提现时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        bankAccountName: {
          type: 'string',
          title: '账户名称',
          ui: {
            placeholder: '请输入'
          }
        },
        accountType: {
          type: 'string',
          title: '账户类型',
          enum: [
            { label: '全部', value: '' },
            { label: '个人合伙人', value: '4' },
            { label: '企业合伙人', value: '5' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        },
        bankType: {
          type: 'string',
          title: '银行类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bankname:type' },
            placeholder: '请输入'
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '提现时间', index: 'createTime', width: 180 },
      { title: '提现单号', index: 'refundApplyCode', width: 120 },
      { title: '网络货运人', index: 'ltdName', width: 140 },
      { title: '银行类型', index: 'bankTypeLabel', width: 100 },
      { title: '账户类型', index: 'accountTypeLabel', width: 100 },
      { title: '账户名称', index: 'bankAccountName', width: 140 },
      { title: '虚拟账户', index: 'virtualAccount', width: 100 },
      {
        title: '提现金额',
        index: 'amount',
        width: 120,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.amount }) }
      },
      { title: '提现银行账户', render: 'bankCardNumber', width: 180 },
      { title: '提现状态', index: 'refundStatusLabel', width: 100 },
      { title: '银行流水号', index: 'bankSerialNumber', width: 120 },
      { title: '核心交易流水', index: 'coreSerNo', width: 130 },
      { title: '备注', index: 'rejectionCause', width: 150, format: item => item.failCause || item.rejectionCause },
      {
        title: '操作',
        fixed: 'right',
        width: '110px',
        className: 'text-center',
        buttons: [
          {
            text: '审核',
            iif: item => item.refundStatus === '1',
            acl: { ability: ['FINANCIAL-WITHDRAWALS-audit'] },
            click: item => this.auditAction(item)
          },
          {
            text: '详情<br>',
            acl: { ability: ['FINANCIAL-WITHDRAWALS-view'] },
            click: item =>
              this.router.navigate([`/financial-management/withdrawals-record/detail/${item.id}`], {
                queryParams: { type: item.accountType }
              })
          },
          {
            text: '查看回单',
            acl: { ability: ['FINANCIAL-WITHDRAWALS-receiptApply'] },
            iif: item => item.refundStatus === '3',
            click: item =>
              this.service.getReceiptUrl(item.receiptUrl, {
                bankType: item.bankType,
                rmYll: item.userId,
                snglFlgCd: item.coreSerNo,
                bussType: '06',
                ltdId: item.ltdId,
                accountType: item.accountType
              })
          }
        ]
      }
    ];
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf?.value,refundStatus: this.refundStatus || null, pageSize: -1 }, this.service.$api_get_asyncExportRefundApplicationList);
  }
}
